import {Module, VuexModule, Mutation, Action, getModule} from 'vuex-module-decorators'
import store from "@/store";
import {Cart} from "@/model/Cart";
import axios from "axios";

/**
 * 参数一：module名称,开启命名空间后会以name为命名空间
 * 参数二：
 */
@Module({name:"cartStore", dynamic:true, store, namespaced:true})
export default class CartStore extends VuexModule{
    public cartItems:Array<Cart> = [];

    @Mutation
    public UPDATE_CART_ITEMS(payload:Array<Cart>){
        this.cartItems = payload;
    }

    @Action
    public getCartItems(){
        axios.get("/api/cart/getCarts").then(({data}) =>{
            const cartItems:Array<Cart> = data as Array<Cart>;
            this.context.commit("UPDATE_CART_ITEMS",cartItems);
        }).catch((error) =>{
            console.log(error);
        })
    }

    @Action
    public addCartItem(cartItem:Cart){
        axios.post("/api/cart/saveCart",cartItem).then(({data}) =>{
            const cartItems:Array<Cart> = data as Array<Cart>;
            this.context.commit("UPDATE_CART_ITEMS",cartItems);
        }).catch((error) =>{
            console.log(error);
        })
    }

    @Action
    public removeCartItem(cartItem:Cart){
        axios.post("/api/cart/deleteCart",cartItem).then(({data}) =>{
            const cartItems:Array<Cart> = data as Array<Cart>;
            this.context.commit("UPDATE_CART_ITEMS",cartItems);
        })
    }

    @Action
    public removeAllCartItems(){
        axios.get("/api/cart/deleteAll").then(({data}) =>{
            const cartItems:Array<Cart> = data as Array<Cart>;
            this.context.commit("UPDATE_CART_ITEMS",cartItems);
        }).catch((error) =>{
            console.log(error);
        })
    }

    public get getAllCarts(){
        return this.cartItems;
    }

    public get cartTotal(){
        return this.cartItems.reduce((acc,cartItem) =>{
            return (cartItem.quantity * cartItem.price) + acc;
        },0).toFixed(2);
    }

    public get cartQuantity(){
        return this.cartItems.reduce((acc,cartItem) =>{
            return cartItem.quantity + acc;
        },0);
    }
}

export const cartStore = getModule(CartStore);
